//
//  VerifyCodeButton.m
//  PigMarket
//
//  Created by Felix on 2019/3/6.
//  Copyright © 2019 felix.pigmarket.oc. All rights reserved.
//

#import "VerifyCodeButton.h"

@interface VerifyCodeButton ()

@property(nonatomic, strong) RACDisposable *countDownDisposable;

@end

@implementation VerifyCodeButton

-(instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self sizeToFit];
        self.isCountDowning = NO;
        self.enabled = NO;
//        @weakify(self)
//        [[RACObserve(self, enabled) distinctUntilChanged] subscribeNext:^(NSNumber *enabled) {
//
//            @strongify(self);
//            UIColor *color = enabled.boolValue ? [UIColor primaryColor] : [UIColor colorWithHexString:@"#a8a8a8"];
//            [self setCornerRadius:4 borderColor:color borderWidth:0.5];
//        }];
        
        [self setNormalText];
        
    }
    return self;
}

- (void)startCountDown {
    
    __block int count = 60;
    [self setCountDownTextWithCount:count];
    self.isCountDowning = YES;
    
    @weakify(self)
    self.countDownDisposable = [[[RACSignal interval:1 onScheduler:[RACScheduler mainThreadScheduler]] take:count] subscribeNext:^(NSDate * _Nullable value) {
        
        @strongify(self)
        
        count--;
        if (count > 0) {
            
            [self setCountDownTextWithCount:count];
            
            self.isCountDowning = YES;
        } else {
            [self setNormalText];
            self.isCountDowning = NO;
        }
    }];
    
}

- (void)setCountDownTextWithCount:(int) count {
//    NSMutableAttributedString *countDownText = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@%ds后可重新获取",(count >= 10 ? @"":@"0"),count]];
//    countDownText.yy_font = [UIFont smallFont];
//    [countDownText yy_setColor:[UIColor primaryColor] range:NSMakeRange(0, 3)];
//    [self setAttributedTitle:countDownText forState:UIControlStateNormal];
//    [self setAttributedTitle:countDownText forState:UIControlStateDisabled];
    NSString *countDownText = [NSString stringWithFormat:@"重新发送(%@%ds)",(count >= 10 ? @"":@"0"),count];
    [self setTitle:countDownText forState:UIControlStateNormal];
    [self setTitle:countDownText forState:UIControlStateDisabled];
}

- (void)setNormalText {
    [self setTitle:@"获取验证码" forState:UIControlStateNormal];
    [self setTitleColor:[UIColor primaryColor] forState:UIControlStateNormal];
    [self setTitleColor:[UIColor lightGrayColor] forState:UIControlStateDisabled];
    self.titleLabel.font = mFont(15);
    
}

- (void)stopCountDown {
    if (![self.countDownDisposable isDisposed]) {
        [self.countDownDisposable dispose];
    }
}

-(void)dealloc {
    [self stopCountDown];
    PMLog(@"%@ is dealloc",NSStringFromClass(self.class));
}


@end
